use std::collections::HashMap;

use crate::*;
use common::grep_result;
use js_sys::{Atomics::wait, Math::sign};
use leptos::leptos_dom::ev::SubmitEvent;
use leptos::logging;
use leptos::*;
use serde::{Deserialize, Serialize};
use serde_json::*;
use tracing::{debug, error, info};

/**
 * 搜索页面,
 * 这是一个典型的调用command，返回结构化数据的案例：
    let args = serde_wasm_bindgen::to_value(&GreetArgs { name: &keyword_val }).unwrap();
    let r = invoke("grep_hello", args).await; 
    let rs:HashMap<String, Vec<grep_result>> = serde_wasm_bindgen::from_value(r).unwrap();
 */
#[component]
pub fn SearchPage() -> impl IntoView {

  let search_result_t:HashMap<String, Vec<grep_result> > = HashMap::new();
  let (sresult, set_sresult) = create_signal( search_result_t);    
  let (keyword, set_keyword) = create_signal( String::new());    

  view! {
    <div align="center">
  <input type="text" size="50" placeholder="input your question!" id="inputbox" on:input=move |ev| set_keyword.set(event_target_value(&ev)) />
          
  <button style="margin:10px" on:click=move |_| {   
    let keyword_val = keyword.get();
    spawn_local(async move {
      let args = serde_wasm_bindgen::to_value(&GreetArgs { name: &keyword_val }).unwrap();
      let r = invoke("grep_hello", args).await; 
      let rs:HashMap<String, Vec<grep_result>> = serde_wasm_bindgen::from_value(r).unwrap();
      logging::log!("{:#?}", rs);

      let search_result_none:HashMap<String, Vec<grep_result> > = HashMap::new();
      set_sresult.set(search_result_none);
      if rs.len() > 0 {
         set_sresult.set(rs);
      }      

      });
    
  }>提问</button>

</div>
<div id="hello">

<Transition fallback=|| view! { <div>"Loading..."</div> } >
    <div> {
        move || {
            let items = sresult.get();          
            items.into_iter().enumerate().map(|(no,item)| {
                view! {
                    <div>{no+1}. {item.0}</div>
                    <div>
                    {  item.1.iter().map(|s| {
                        let line = s.line_no;
                        view! {
                          <li>"[ line : " {line} " ] " {s.line_prefix.clone()}<mark>{s.mit_word.clone()}</mark>{s.line_end.clone()}</li>
                        }
                        }).collect_view()                   
                    }                   
                    </div><br/>
                }
            })
            .collect_view()                      
        }
    }                        
    </div>
</Transition>

</div>

    }
}
